/*
 * @Author: shiguo
 * @Date: 2022-04-25 17:56:29
 * @LastEditors: shiguo
 * @LastEditTime: 2022-09-19 11:55:45
 * @FilePath: /@aks-dev/umeng/android/src/main/java/com/umeng/RNUpushModule.java
 */

package com.umeng;

import android.os.Handler;
import android.os.Looper;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

public class RNUpushModule extends ReactContextBaseJavaModule {

    private static final String TAG = "RNUpushModule";
    private final ReactApplicationContext context;
    private static boolean isInit = false;

    public RNUpushModule(ReactApplicationContext context) {
        super(context);
        this.context = context;
        UMPushHelper.getInstance().reactContext = context;
    }


    @Override
    public String getName() {
        return "RNUpushModule";
    }


    @ReactMethod
    public void init(final Promise promise) {

        String deviceToken = UMPushHelper.getInstance().deviceToken;
        if (deviceToken != null && deviceToken.length() > 0) {
            promise.resolve(deviceToken);
        } else {
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() {
                    UMCommonHelper.getInstance().init();
                    UMPushHelper.getInstance().setPushSetting();
                    UMPushHelper.getInstance().register(new UMPushHelper.IRegister() {
                        @Override
                        public void onSuccess(String deviceToken) {
                            promise.resolve(deviceToken);
                        }

                        @Override
                        public void onFailure(String errCode, String errDesc) {
                            promise.resolve(errDesc);
                        }
                    });
                    UMPushHelper.getInstance().registerDevicePush();
                }
            });

        }
    }


}